<template>
  <el-form :model="form" label-width="100px" class="form-container" style="margin-top: 100px">
    <el-row :gutter="20">
      <!-- 左侧栏 -->
      <el-col :span="8">
        <el-form-item label="单据编号：">
          <el-input
              v-model="form.code"
              placeholder="请输入"
              clearable
          />
        </el-form-item>

        <el-form-item label="单据阶段：">
          <el-select
              v-model="form.stage"
              placeholder="请选择"
              clearable
          >
            <el-option
                label="已生效"
                value="active"
                :checked="form.stage === 'active'"
            />
            <!-- 其他选项可根据需要添加 -->
          </el-select>
        </el-form-item>
      </el-col>

      <!-- 中间栏 -->
      <el-col :span="10">
        <el-form-item label="单据日期：">
          <el-date-picker
              v-model="form.dateRange"
              type="daterange"
              range-separator="至"
              :start-placeholder="form.dateRange[0] || '请选择开始'"
              :end-placeholder="form.dateRange[1] || 'A'"
          />
        </el-form-item>

        <el-form-item label="已作废：">
          <el-select v-model="form.invalid" placeholder="否">
            <el-option label="否" value="no" />
            <el-option label="是" value="yes" />
          </el-select>
        </el-form-item>



      </el-col>



      <!-- 右侧操作按钮 -->
      <el-col :span="6" class="action-buttons">
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button type="info" @click="handleReset">重置</el-button>
        <el-button type="success" @click="toggleCollapse">收</el-button>
      </el-col>

      <el-col :span="6">

        <el-form-item label="盘点人" prop="checkManId">

          <el-select
              v-model="form.checkManId"
              placeholder="请选择盘点人"
              style="width: 240px"
              clearable
              filterable
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name}`"
                :value="user.id"
            />
          </el-select>

        </el-form-item>
      </el-col>

    </el-row>
  </el-form>

  <div>
    <InventoryLossPageUtil style="margin-top: 20px"
                           :table-data="tableData"
                           :columns="tableColumns"
                           :current-page="pageNo"
                           :total="total"
                           :page-size="pageSize"
                           @page-change="handlePageChange"
                           @action="handleTableAction"
                           @code-click = "updateInventory"
                           @edit="updateInventory"
                           @delete="del"
                           @selection-change="handleSelectionChange"
                           @row-audit="handleRowAudit"
    ></InventoryLossPageUtil>

    <el-dialog
        v-model="auditDialogVisible"
        title="单据审核"
        width="600px"
        :close-on-click-modal="false"
    >
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef">
        <el-form-item label="单据编号：" prop="code">
          <el-input
              v-model="auditForm.code"
              disabled
              placeholder="系统自动填充"
          />
        </el-form-item>

        <el-form-item label="审核人：" prop="auditor">
          <el-select
              v-model="auditForm.auditor"
              placeholder="请选择审核人"
              filterable
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="user in userList"
                :key="user.id"
                :label="`${user.name} `"
                :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="审批意见：" prop="comment">
          <el-input
              v-model="auditForm.comment"
              type="textarea"
              :rows="3"
              placeholder="请输入审批意见"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
        <el-form-item label="审核结果：" prop="checkResult">
          <el-select
              v-model="auditForm.checkRes"
              placeholder="请选择审核结果"
              style="width: 100%"
          >
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>

      </el-form>

      <template #footer>
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>
  </div>


</template>

<script setup lang="ts">
import { ref,reactive, toRaw } from 'vue';
import axios from 'axios';
import SalesOrderPage from '@/sales-order/SalesOrderPage.vue';
import { useRoute,useRouter } from 'vue-router';
import type { SalesOrder } from '@/types/public-xs/salesDocuments';
import { ElMessage } from 'element-plus';
import BuyInStorePageUtil from "@/kc-view/instore/buy-inStore/BuyInStorePageUtil.vue";
import InventoryCheckPageUtil from "@/kc-view/inventory-check/InventoryCheckPageUtil.vue";
import InventoryProfitPageUtil from "@/kc-view/inventory-profit/InventoryProfitPageUtil.vue";
import InventoryLossPageUtil from "@/kc-view/inventory-loss/InventoryLossPageUtil.vue";
import type {User} from "@/types/rs/User.ts";
import request from "@/util/request.ts";

let pageNo=ref(1)
let pageSize=ref(3)
let total=ref(0)
let route=useRoute()
let router=useRouter()
const form = reactive({
  code: '',
  checkManId: '',
  stage: 'active',
  dateRange: [],
  invalid: 'no',
  subject: ''
})


// 新增响应式数据
const auditDialogVisible = ref(false);
const auditFormRef = ref();
const auditForm = reactive({
  code: '',
  auditor: '',
  comment: '',
  checkRes: null
});

let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

// 表单验证规则
const auditRules = reactive({
  auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
  comment: [{ required: true, message: '请输入审批意见', trigger: 'blur' }],
  checkRes: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
});
// 审核方法
const handleRowAudit = (row: any) => {
  auditForm.code = row.code
  auditDialogVisible.value = true
  console.log('当前审核单据:', row.code)
}
const submitAudit = async () => {
  // 表单验证
  if (!await auditFormRef.value?.validate()) return;

  // const rawArray = toRaw(selectedDocs.value);
  // const docCodeValue = rawArray[0];


  try {
    const response = await request.post('kc/inventoryProfit/check', {
      code: auditForm.code,
      typeId: 42,
      status: 3,
      checkManId: auditForm.auditor,  // 绑定审核人ID
      checkComment: auditForm.comment, // 绑定审批意见
      checkRes: auditForm.checkRes // 绑定审核结果
    });
    let response1=await request.post('kc/inventoryProfit/getInventoryProfitList',{
      code:auditForm.code,
    })

    let response2 = await request.post('kc/inventoryProfitDetail/getInventoryProfitDetailList', {
      inventoryProfitCode:auditForm.code
    },{
      headers:{
        'Content-Type':'application/x-www-form-urlencoded'
      }
    });
    console.log(response1.data.data)
    console.log(response2.data.data)

    if(response1.data.data.list[0].orderStatus==3){
      if(response2.data.data!=null&&response2.data.data.length>0){
        response2.data.data.forEach(item=>{
          let response4 = request.post('kc/StoreGoodSummary/method',{
                sid:response1.data.data.list[0].storeId,
                gid:item.goodId,
                stock:item.inventoryProfitNum,
                sumCost:item.sumCost
              },
          )
        })
      }
    }

    ElMessage.success('审核成功');
    auditDialogVisible.value = false;
    fetchData(pageNo.value); // 刷新表格数据
  } catch (error) {
    ElMessage.error('审核提交失败');
  } finally {
    // 重置表单
    auditForm.auditor = '';
    auditForm.comment = '';
  }
};

const handleQuery = () => {
  // 重置为第一页
  pageNo.value = 1
  fetchData(pageNo.value)
  // 传递表单查询参数
  // fetchData(pageNo.value, {
  //   doCode: form.docNumber,
  //   stage: form.stage,
  //   invalid: form.invalid,
  //   startDate: form.dateRange[0] ? formatDate(form.dateRange[0]) : undefined,
  //   endDate: form.dateRange[1] ? formatDate(form.dateRange[1]) : undefined
  // })
}

const handleReset = () => {
  Object.assign(form, {
    docNumber: '',
    stage: 'active',
    dateRange: [],
    invalid: 'no',
    subject: ''
  })
}

const del=async (row: any) => {
  if (!confirm('你确定要删除吗？')) {
    return
  }
  let response = await request.get('kc/inventoryProfit/delInventoryProfit', {
    params:{
      code:row.code
    }
  })

  if(response.data.data){
    ElMessage.success('删除成功')
    pageNo.value=1
    await fetchData(pageNo.value)
  }else{
    ElMessage.error('删除失败')
  }



}

const toggleCollapse = () => {
  // 收起/展开逻辑
}

const tableColumns = ref([
  { prop: 'code', label: '单据编号', width: 200 },
  { prop: 'orderDate', label: '单据日期', width: 200 },
  { prop: 'orderStatus', label: '单据状态', width: 200 },
  { prop: 'deptName', label: '部门名称', width: 200 },
  { prop: 'storeName', label: '盘点仓库', width: 200 },
  { prop: 'checkManName', label: '盘点员', width: 200 },
  { prop: 'typeName', label: '业务类型', width: 200 },
  { prop: 'createName', label: '创建者名称', width: 200 },
  { prop: 'createDate', label: '创建日期', width: 200 },
  { prop: 'updateName', label: '更新者名称', width: 200 },
  { prop: 'updateDate', label: '更新日期', width: 200 }
])

let tableData=ref([])
const handlePageChange = (newPage: number) => {
  pageNo.value = newPage;
  fetchData(newPage);
}
// const formatDate = (date: Date, isEndDate: boolean = false) => {
//   const pad = (num: number) => num.toString().padStart(2, '0');
//   const year = date.getFullYear();
//   const month = pad(date.getMonth() + 1);
//   const day = pad(date.getDate());
//
//   // 如果是结束日期，时间设为 23:59:59
//   if (isEndDate) {
//     return `${year}-${month}-${day} 23:59:59`;
//   }
//   return `${year}-${month}-${day} 00:00:00`;
// };


const handleTableAction = (actionName: string) => {
  switch(actionName){
    case 'add':
      router.push('/home/inventoryProfit/add')
      break
    case'check':
      handleCheck()
      break;
  }
}

async function fetchData(page: number) {
  // const [startDate, endDate] = form.dateRange || []
  let params = {
    pageNo: page,
    pageSize: pageSize.value,
    code:form.code,
    checkManId:form.checkManId
    // customerName:form.customerName
    // doCode: form.docNumber,
    // stage: form.stage,
    // invalid: form.invalid,
    // startDate: startDate ? formatDate(startDate) : undefined,
    // endDate: endDate ? formatDate(endDate) : undefined
  }

  let response=await request.post('kc/inventoryProfit/getInventoryProfitList',{
    ...params,
    // ...queryParams
  })
  tableData.value=response.data.data.list
  console.log(tableData.value)
  total.value=response.data.data.total

}
fetchData(1)
const updateInventory=(row: any)=>{
  router.push({
    name:'EditInventoryProfit',
    params:{
      code: row.code // 传递单据编号
    }
  })

}

const selectedDocs = ref<string[]>([])

// 监听子组件选择事件
const handleSelectionChange = (selection: SalesOrder[]) => {
  selectedDocs.value = selection.map(row => row.docCode)
}

// 审核方法
const handleCheck = async () => {
  if (selectedDocs.value.length === 0) {
    ElMessage.warning('请至少选择一条需要审核的单据')
    return
  }
  const rawArray = toRaw(selectedDocs.value);
  const docCodeValue = rawArray[0];
  try {
    const response = await request.post('xs/salesOrder/check', {
      docCode:docCodeValue,
      typeId:2,
    })
    ElMessage.success(response.data.msg)
    fetchData(pageNo.value) // 刷新数据
  } catch (error) {
    ElMessage.error('审核失败')
  }
}




</script>

<style scoped>

</style>
